<script setup lang="ts">
import { loginApi } from '@/apis/user';
import { useUserStore } from '@/stores/user';
import type { LoginForm } from '@/types/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';

// 登录表单数据
const form = ref<LoginForm>(localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : {
  username: '', // demo
  password: '' // Hmzs%001
})
// 记住账号密码
const remember = ref(JSON.parse(localStorage.getItem('remember') as string) || false)
// 表单验证规则
const rules = ref<FormRules>({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
  ]
})
// 创建表单实例
const formRef = ref<FormInstance>()
// 登录
const router = useRouter()
const store = useUserStore()
const login = async () => {
  // 表单验证
  await formRef.value?.validate()
  const res = await loginApi(form.value)
  // console.log(res);
  // 保存token
  store.setToken(res.data.token)
  // 记住我,选中就保存到本地,否则就在本地删除
  localStorage.setItem('remember', JSON.stringify(remember.value))
  if (remember.value) {
    localStorage.setItem('userInfo', JSON.stringify(form.value))
  } else {
    localStorage.removeItem('userInfo')
  }
  ElMessage.success('登录成功')
  router.push('/')
}
</script>

<template>
  <div class="login-page">
    <el-card>
      <el-form label-position="top" :model="form" :rules="rules" ref="formRef">

        <el-form-item label="账号:" prop="username">
          <el-input placeholder="请输入账号" v-model="form.username" />
        </el-form-item>

        <el-form-item label="密码:" prop="password">
          <el-input placeholder="请输入密码" type="password" v-model="form.password" maxlength="16" />
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="remember">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      {{ form }}{{ remember }}
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;

  .el-card {
    width: 450px;
    margin: 0 auto;
    margin-top: 150px;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .el-form-item {
      margin-bottom: 20px;

      .el-button {
        width: 100%;
        height: 40px;
      }
    }
  }
}
</style>
